/**
 * 会计期间 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.GLPeriod.MainForm", {
  extend: "PSI.AFX.Form.MainForm",

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      tbar: me.getToolbarCmp(),
      items: [{
        region: "north",
        height: 55,
        border: 0,
        margin: 0,
        bodyPadding: "0 20 0 15",
        html: `<h2 style='color:#595959;display:inline-block'>会计期间</h2>
                &nbsp;&nbsp;<span style='color:#8c8c8c'>初始化会计期间及状态查询</span>`,
      }, {
        region: "west",
        width: 770,
        layout: "fit",
        border: 0,
        split: true,
        bodyPadding: "0 0 5 15",
        items: [me.getCompanyGrid()]
      }, {
        region: "center",
        xtype: "panel",
        layout: "border",
        border: 0,
        bodyPadding: "0 20 5 0",
        items: [{
          region: "center",
          layout: "fit",
          split: true,
          border: 0,
          items: me.getMainGrid()
        }]
      }]
    });

    me.callParent(arguments);

    me.refreshCompanyGrid();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;
    return [{
      iconCls: "PSI-tb-new",
      text: "初始化会计期间",
      ...PSI.Const.BTN_STYLE,
      handler: me._onInitPeriod,
      scope: me
    }, "-", {
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("/Home/Help/index?t=glperiod"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    }, {
      // 空容器，只是为了撑高工具栏
      xtype: "container", height: 28,
      items: []
    }].concat(me.getShortcutCmp());
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * @private
   */
  refreshCompanyGrid() {
    const me = this;
    const el = PCL.getBody();
    const store = me.getCompanyGrid().getStore();
    el.mask(PSI.Const.LOADING);
    const r = {
      url: me.URL("SLN0002/GLPeriod/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (store.getCount() > 0) {
            me.getCompanyGrid().getSelectionModel().select(0);
          }
        }

        el.unmask();
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  getCompanyGrid() {
    const me = this;
    if (me._companyGrid) {
      return me._companyGrid;
    }

    const modelName = me.buildModelName(me, "GLPeriod_Company");

    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "orgType", "currentPeriod", "initPeriod", "glInitDT", "detailInitDT"]
    });

    me._companyGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      header: {
        height: 30,
        title: me.formatGridHeaderTitle(me.toTitleKeyWord("核算组织机构"))
      },
      columnLines: true,
      columns: [{
        header: "编码",
        dataIndex: "code",
        menuDisabled: true,
        sortable: false,
        width: 70
      }, {
        header: "组织机构名称",
        dataIndex: "name",
        width: 200,
        menuDisabled: true,
        sortable: false,
        renderer(value) {
          return me.toAutoWrap(value);
        }
      }, {
        header: "组织机构性质",
        dataIndex: "orgType",
        width: 100,
        menuDisabled: true,
        sortable: false
      }, {
        header: "当前会计期间",
        dataIndex: "currentPeriod",
        width: 100,
        menuDisabled: true,
        sortable: false,
        align: "center",
      }, {
        header: "建账",
        columns: [
          {
            header: "建账期初期间",
            dataIndex: "initPeriod",
            width: 100,
            menuDisabled: true,
            sortable: false,
            align: "center",
          }, {
            header: "总分类账建账时间",
            dataIndex: "glInitDT",
            width: 150,
            menuDisabled: true,
            sortable: false
          }, {
            header: "明细分类账建账时间",
            dataIndex: "detailInitDT",
            width: 150,
            menuDisabled: true,
            sortable: false
          }
        ],
      },],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onCompanyGridSelect,
          scope: me
        }
      }
    });
    return me._companyGrid;
  },

  /**
   * @private
   */
  _onCompanyGridSelect() {
    const me = this;

    me.getMainGrid().setTitle(me.formatGridHeaderTitle("会计期间"));
    const item = me.getCompanyGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const company = item[0];

    const title = me.toTitleKeyWord(company.get("name")) + " - 会计期间";
    me.getMainGrid().setTitle(me.formatGridHeaderTitle(title));

    const grid = me.getMainGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);

    const r = {
      url: me.URL("SLN0002/GLPeriod/periodList"),
      params: {
        companyId: company.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el?.unmask();
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;
    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "PeriodGrid");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "year", "month", "glClosed", "detailClosed", "periodClosed",
        "memo"
      ]
    });

    const defaultColsProp = {
      menuDisabled: true,
      sortable: false,
      draggable: false
    };

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("会计期间")
      },
      emptyText: me.toEmptyText("尚未初始化会计期间"),
      columnLines: true,
      columns: {
        defaults: defaultColsProp,
        items: [{
          header: "年",
          dataIndex: "year",
          width: 60,
          align: "center"
        }, {
          header: "月",
          dataIndex: "month",
          width: 60,
          align: "center"
        }, {
          header: "",
          dataIndex: "memo",
          width: 100,
        }, {
          header: "明细分类账已关账",
          dataIndex: "detailClosed",
          width: 150,
          align: "center",
        }, {
          header: "总分类账已关账",
          dataIndex: "glClosed",
          width: 150,
          align: "center",
        }, {
          header: "本期间已结账",
          dataIndex: "periodClosed",
          width: 150,
          align: "center"
        },]
      },
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      })
    });

    return me._mainGrid;
  },

  /**
   * 初始化本年度会计期间
   * 
   * @private
   */
  _onInitPeriod() {
    const me = this;
    const item = me.getCompanyGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const company = item[0];

    const form = PCL.create("PSI.SLN0002.GLPeriod.SelectPeriodForm", {
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
      company,
    });
    form.show();
  }
});
